package com.example.Reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        // 获取 Class 对象
//        Class<?> clazz = Person.class;
        Class<?> clazz = Person.class;
//
        // 创建对象Constructor
        Constructor<?> constructor = clazz.getConstructor(String.class,int.class);
//        Constructor<?> constructor = clazz.getConstructor(String.class,int.class);
//        Object person = constructor.newInstance("John", 30);
        Object person = constructor.newInstance("邓先生",24);
        // 访问字段
        Field nameField = clazz.getDeclaredField("name");
        Field ageField = clazz.getDeclaredField("age");
        nameField.setAccessible(true); // 设置属性可读
        ageField.setAccessible(true);
        System.out.println(nameField.get(person));
        System.out.println(ageField.get(person));


        // 修改字段
        nameField.set(person,"邓天帝");
        ageField.set(person,9999999);
        System.out.println("Updated Name: " + nameField.get(person));
        System.out.println("Updated Age: " + ageField.get(person));

        // 调用方法
        Method greetMethod = clazz.getMethod("greet", String.class);
        greetMethod.invoke(person,"我乃邓天帝！！！");

        Method eatMethod = clazz.getMethod("eat", String.class);
        eatMethod.invoke(person,"六脉神剑");

    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void greet(String message) {
        System.out.println(name + " says: " + message);
    }

    public void eat(String jinengs){
        System.out.println(name + " 释放技能: " + jinengs);
    }
}
